extends Node2D

#代码由deepseek生成

var sway_amplitude# 水平摆动幅度
var rotation_speed# 旋转速度
var tween=Tween.new()
var control_points#曲线点


func _ready():
	scale=Vector2(rand_range(0.2,0.25),rand_range(0.2,0.25))
	sway_amplitude=rand_range(80,300)
	rotation_speed=rand_range(-2.0,2.0)
	control_points=[
		position,
		Vector2(position.x+sway_amplitude,position.y+(512-position.y)/3+rand_range(-100,100)),
		Vector2(position.x-sway_amplitude,position.y+((512-position.y)/3)*2+rand_range(-100,100)),
		Vector2(position.x+sway_amplitude,512)
	]
	var duration=7
	add_child(tween)
	# 垂直下落
	tween.interpolate_property(self,"position:y",
		position.y,600,duration,
		Tween.TRANS_LINEAR,Tween.EASE_IN)
	# 水平摆动（贝塞尔曲线实现自然摆动）
	tween.interpolate_method(self,"apply_bezier_sway",0.0,1.0,duration)
	# 旋转动画
	tween.interpolate_property(self,"rotation",
		0,rotation_speed*PI,duration,
		Tween.TRANS_QUAD,Tween.EASE_IN_OUT)
	tween.start()
	yield(tween,"tween_completed")
	queue_free()


#func _draw():
#	if control_points.size() < 2: return
#	# 绘制控制点连线
#	draw_polyline(control_points, Color.red, 1.0)
#	# 绘制实际运动轨迹
#	var curve_points := []
#	for t in 20:
#		curve_points.append(bezier(control_points, t/20.0))
#	draw_polyline(curve_points, Color.green, 2.0)


func bezier(points: Array, t: float) -> Vector2:
	if points.size() == 1:
		return points[0]
	var new_points := []
	for i in range(points.size()-1):
		var p = points[i].linear_interpolate(points[i+1], t)
		new_points.append(p)
	return bezier(new_points, t)


func apply_bezier_sway(t:float):
	var target = bezier(control_points, t)
	position.x = target.x
